package com.hls.zfbai.modules.business.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hls.zfbai.core.utils.CommonConstants;
import com.hls.zfbai.core.utils.HttpClientUtil;
import com.hls.zfbai.core.utils.XmlUtils;
import com.hls.zfbai.modules.business.entity.*;
import com.hls.zfbai.modules.business.entity.hlwyy.JcbgEventReqParam;
import com.hls.zfbai.modules.common.dao.CommonMapper;
import com.hls.zfbai.modules.common.entity.GyXtcs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Service
public class JcbgPushService {
    @Resource
    private MqPtJcbgService mqPtJcbgService;
    @Resource
    private ZfbAiService zfbAiService;
    @Resource
    private CommonMapper commonMapper;
    @Resource
    private EmrJcsqService emrJcsqService;

    @Scheduled(fixedRate = 1000)
    public void run() {
        LocalDateTime localDateTime = LocalDateTime.now();
        QueryWrapper<MqPtJcbg> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql("JLXH","SELECT JLXH FROM MQ_PT_JCBG WHERE JLSJ > SYSDATE - 5/1440 AND TSBZ = 0");
        List<MqPtJcbg> mqPtJcbgList = mqPtJcbgService.list(queryWrapper);

        log.info("获取未推送的检查报告...");

        if(!CollectionUtils.isEmpty(mqPtJcbgList)) {
            log.info("获取未推送的检查报告，共获取到信息数：{}条", mqPtJcbgList.size());
            for(MqPtJcbg mqPtJcbg : mqPtJcbgList) {
                this.sendWx(mqPtJcbg);
                //更新推送状态
                mqPtJcbg.setTsbz(1);
                mqPtJcbg.setTssj(localDateTime);
                mqPtJcbgService.updateById(mqPtJcbg);
            }
        } else {
            log.info("获取未推送的检查报告，共获取到信息数：0条");
        }
    }

    /**
     * 报告出具推送（支付宝AI陪诊）
     * @param mqPtJcbg
     */
    public void bgcj(MqPtJcbg mqPtJcbg) {
        GyXtcs qycsCs = new GyXtcs("1", "ZFBAI_SERVICE_SFQY", "0", "支付宝AI云陪诊接口是否启用");
        commonMapper.getXtcs(qycsCs);
        String qycs = qycsCs.getCSZ();
        GyXtcs qyghCs = new GyXtcs("1", "ZFBAI_SERVICE_SFQY_JCBG", "0", "支付宝AI云陪诊接口是否启用");
        commonMapper.getXtcs(qyghCs);
        String qyjc = qyghCs.getCSZ();
        if(CommonConstants.YES.equals(qycs) && CommonConstants.YES.equals(qyjc)) {
            String jzlx = this.getJzlx(mqPtJcbg);
            if(CommonConstants.YES.equals(jzlx)) {
                String sqdh = mqPtJcbg.getElectrRequisitionNo();
                if(StringUtils.isNotBlank(sqdh)) {
                    Map<String, Object> msYj01 = zfbAiService.jcbgcj(sqdh);
                    if(!Objects.isNull(msYj01)) {
                        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                        LocalDateTime localDateTime = LocalDateTime.now();
                        String now = dateTimeFormatter.format(localDateTime);
                        String zlxmmc = mqPtJcbg.getExamItemName();
                        zlxmmc += mqPtJcbg.getExamCategName();

                        BgcjParam bgcjParam = new BgcjParam();
                        bgcjParam.setTradeCode("1001");
                        bgcjParam.setDatasetCode("HDSD.MZJZJL");
                        bgcjParam.setMedHosCode(msYj01.getOrDefault("YQSB", "1").toString());
                        bgcjParam.setMzlsh(msYj01.getOrDefault("JZXH", "0").toString());
                        bgcjParam.setGhlsh(msYj01.getOrDefault("GHXH", "0").toString());
                        bgcjParam.setSjlx("bgcj");
                        bgcjParam.setSjbm(sqdh + "_bgcj");
                        bgcjParam.setSjfssj(now);
                        bgcjParam.setScbs("0");
                        bgcjParam.setSjgxsj(now);
                        bgcjParam.setSjxmdm(msYj01.getOrDefault("YJXH", "0").toString());
                        bgcjParam.setSjxmmc(zlxmmc);
                        bgcjParam.setBgdh(mqPtJcbg.getReportNo());
                        bgcjParam.setBgdmc(zlxmmc + "报告结果");
                        bgcjParam.setTxnr(zlxmmc + "报告已出，请及时查看");
                        //推送接口
                        zfbAiService.bgcj(bgcjParam);
                    }
                }
            }
        }
    }

    /**
     * 报告推送微信
     * @param mqPtJcbg
     */
    public void sendWx(MqPtJcbg mqPtJcbg) {
        String jzlx = this.getJzlx(mqPtJcbg);
        String sqdh = mqPtJcbg.getElectrRequisitionNo();
        if(StringUtils.isNotBlank(sqdh) && StringUtils.isNotBlank(jzlx)) {
            EmrJcsq emrJcsq = emrJcsqService.getById(Long.parseLong(sqdh));
            if(!Objects.isNull(emrJcsq)) {
                JcbgEventReqParam jcbgEventReqParam = new JcbgEventReqParam();
                jcbgEventReqParam.setEventNo(UUID.randomUUID().toString().replace("-", ""));
                jcbgEventReqParam.setEventType("pacsReportCompleted");
                JcbgEventReqParam.JcbgEventData jcbgEventData = new JcbgEventReqParam.JcbgEventData();

                if(CommonConstants.COMMON_NUMBER_ONE.equals(jzlx)) {
                    jcbgEventData.setClinicSeq(emrJcsq.getJzhm());
                    jcbgEventData.setPatientId(emrJcsq.getBrid().toString());
                } else {
                    jcbgEventData.setInpatientId(mqPtJcbg.getPatientId());
                }

                jcbgEventData.setReportId(mqPtJcbg.getReportNo());
                jcbgEventData.setReportTitle(mqPtJcbg.getExamItemName());
                jcbgEventData.setExameDate(mqPtJcbg.getExamDate());
                jcbgEventData.setReportDate(mqPtJcbg.getExamReportDate());

                jcbgEventReqParam.setEventData(jcbgEventData);
                String param = XmlUtils.convertToXml(jcbgEventReqParam);
                log.info("检查报告推送微信，入参：{}", param);
                GyXtcs urlXtcs = new GyXtcs("1", "SEND_WXZYD_URL", "http://192.168.230.20:6888", "微信指引单接口路径");
                commonMapper.getXtcs(urlXtcs);
                String url = urlXtcs.getCSZ();
                GyXtcs methodXtcs = new GyXtcs("1", "SEND_WXZYD_METHOD", "/interface-service-v3/notify", "微信指引单接口方法");
                commonMapper.getXtcs(methodXtcs);
                String method = methodXtcs.getCSZ();
                String rsp = HttpClientUtil.postMethod(url + method, param, "", "");
                log.info("检查报告推送微信，出参：{}", rsp);
            }
        }
    }

    public String getJzlx(MqPtJcbg mqPtJcbg) {
        String patTypeCode = mqPtJcbg.getPatTypeCode();
        String examPatResourceCode = mqPtJcbg.getExamPatResourceCode();
        if(CommonConstants.COMMON_NUMBER_ONE.equals(patTypeCode) || CommonConstants.COMMON_NUMBER_ONE.equals(examPatResourceCode)) {
            return CommonConstants.COMMON_NUMBER_ONE;
        } else if(CommonConstants.COMMON_NUMBER_TWO.equals(patTypeCode) || CommonConstants.COMMON_NUMBER_THREE.equals(examPatResourceCode)) {
            return CommonConstants.COMMON_NUMBER_TWO;
        } else {
            return CommonConstants.COMMON_STRING_EMPTY;
        }
    }

}